import 'package:bilibili/core/HiState.dart';
import 'package:bilibili/http/core/hi_error.dart';
import 'package:bilibili/http/dao/home_dao.dart';
import 'package:bilibili/model/home_mo.dart';
import 'package:bilibili/navigator/hi_navigator.dart';
import 'package:bilibili/page/home_tab_page.dart';
import 'package:bilibili/util/color.dart';
import 'package:bilibili/util/toast.dart';
import 'package:bilibili/widget/navigator_bar.dart';
import 'package:flutter/material.dart';

class HomePage extends StatefulWidget {
  final ValueChanged<int>? onJumpTo;

  const HomePage({super.key, this.onJumpTo});

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends HiState<HomePage>
    with AutomaticKeepAliveClientMixin, TickerProviderStateMixin {
  RouteChangeListener? listener;
  TabController? _controller;

  List<BannerMo>? bannerList = [];
  List<CategoryMo>? categoryList = [];

  @override
  void initState() {
    super.initState();
    _loadData();
    _controller = TabController(length: categoryList!.length, vsync: this);
    HiNavigator.getInstance().addListener(listener = (current, pre) {
      if (widget == current.page || current.page is HomePage) {
        print("home onResume");
      } else if ((widget == pre.page || pre.page is HomePage)) {
        print("home onPause");
      }
    });
  }

  // 切换页面不会被销毁
  @override
  bool get wantKeepAlive => true;

  @override
  void dispose() {
    // if (listener != null) {
    //   HiNavigator.getInstance().removeListener(listener!);
    // }

    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Scaffold(
      body: Column(
        children: [
          NavigatorBar(
            height: 50,
            color: Colors.white,
            statusStyle: StatusStyle.DARK_CONTENT,
            child: _appBar(),
          ),
          Container(
              color: Colors.white,
              padding: EdgeInsets.only(top: 0),
              child: _tabBar()),
          Flexible(
              child: TabBarView(
                  controller: _controller, //没有做特殊处理就能联动，是因为共用了controller
                  children: categoryList!.map((tab) {
                    return HomeTabPage(
                        name: tab.name,
                        bannerList: tab.name == '推荐' ? bannerList : null);
                  }).toList()))
        ],
      ),
    );
  }

  _tabBar() {
    return TabBar(
        controller: _controller,
        isScrollable: true,
        dividerHeight: 0, // 去除底部黑线
        tabAlignment: TabAlignment.start, //去除左侧空白
        labelColor: Colors.black,
        indicator: UnderlineTabIndicator(
            borderSide: BorderSide(color: primary, width: 3),
            insets: EdgeInsets.only(left: 0, right: 0)),
        tabs: categoryList!.map<Tab>((tab) {
          return Tab(
              child: Padding(
                  padding: EdgeInsets.only(top: 20, left: 5, right: 5),
                  child: Text(
                    tab.name ?? "",
                    style: TextStyle(fontSize: 16),
                  )));
        }).toList());
  }

  _appBar() {
    return Padding(
      padding: EdgeInsets.only(left: 15, right: 15),
      child: Row(
        children: [
          InkWell(
            onTap: () {
              if (widget.onJumpTo != null) {
                widget.onJumpTo!(3);
              }
            },
            child: ClipRRect(
              borderRadius: BorderRadius.circular(23),
              child: Image(
                  width: 46,
                  height: 46,
                  image: AssetImage('assets/images/avatar.png')),
            ),
          ),
          Expanded(
              child: Padding(
            padding: EdgeInsets.only(left: 15, right: 15),
            child: ClipRRect(
              borderRadius: BorderRadius.circular(16),
              child: Container(
                padding: EdgeInsets.only(left: 10),
                decoration: BoxDecoration(color: Colors.grey[100]),
                height: 32,
                alignment: Alignment.centerLeft,
                child: Icon(
                  Icons.search,
                  color: Colors.grey,
                ),
              ),
            ),
          )),
          Icon(
            Icons.explore_outlined,
            color: Colors.grey,
          ),
          Padding(
            padding: EdgeInsets.only(left: 12),
            child: Icon(
              Icons.email_outlined,
              color: Colors.grey,
            ),
          )
        ],
      ),
    );
  }

  void _loadData() async {
    try {
      HomeMo result = await HomeDao.get("推荐");
      print(result);
      if (result.categoryList != null) {
        _controller =
            TabController(length: result.categoryList!.length, vsync: this);
      }
      setState(() {
        bannerList = result.bannerList;
        categoryList = result.categoryList;
      });
    } on HiNetError catch (e) {
      print(e);
      showWarningToast(e.message);
    }
  }
}
